# coding: utf-8
from addon.common.addon import Addon
from addon.common.net import Net
#from metahandler import metahandlers
import xbmc,xbmcplugin,xbmcgui,xbmcaddon,xbmcvfs
import urllib,urllib2,re,os,sys,htmllib,string,StringIO,logging,random,array,time,datetime
import unicodedata
import urlresolver
import copy
import HTMLParser
from t0mm0.common.addon import Addon







# 501-POSTER WRAP 503-MLIST3 504=MLIST2 508-FANARTPOSTER 
#confluence_views = [500,501,502,503,504,508]


addon = Addon('plugin.video.frenchstream', sys.argv)
xaddon = xbmcaddon.Addon(id='plugin.video.frenchstream')
AddonPath = xaddon.getAddonInfo('path')
IconPath = AddonPath + "/icons/"

def CATEGORIES():
	
	page='1'
	addDir('LES NOUVEAUTÉS','http://frenchstream.net/page/'+page,1,IconPath +'nouveautes.png')
	addDir('LES PLUS VUS','http://frenchstream.net/les-plus-vus/page/'+page,1,IconPath +'plusvus.png')
	addDir('LES PLUS COMMENTÉES','http://frenchstream.net/les-plus-commentees/page/'+page,1,IconPath +'commentees.png')
	addDir('LES MIEUX AIMÉS','http://frenchstream.net/les-mieux-aimes/page/'+page,1,IconPath +'aimes.png')
	addDir('RECHERCHE',' ',3,IconPath +'recherche.png')
	
	
	




###################################################################################

def INDEX(url):
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	link=link.decode('utf-8')
	match=re.compile('<a href="(.+?)">\s*<span class="tr-dublaj"></span>\s*<img src="(.+?)" alt="(.+?)"').findall(link)	
	#[match.pop() for x in range(0, 5)]
	match=[(x,y,HTMLParser.HTMLParser().unescape(z)) for x,y,z in match] 
	for url,thumb,name in match:
                addDir(name,url,2,thumb)


###################################################################################

def FILMPAGE(url):
	response = urllib2.urlopen(url)
	link=response.read()
	response.close()  
	match=re.compile('<div class="filmaltiimg">\s*<img src="(.+?)" alt', re.IGNORECASE).findall(link)
	thumb=str(match[0])

	
	num=1
	for x in range(0,6):
		page=str(num)
		link=url+'/'+page
		num +=1
		response = urllib2.urlopen(link)
		link=response.read()
		response.close()  
		match=re.compile('<!--baslik:(.+?)--><br />\s*<.*?src="(.+?)"', re.IGNORECASE).findall(link)
		match=str(match[0])
		match=HTMLParser.HTMLParser().unescape(match)
		match=str(match)
		match=match.replace('(\'','')
		match=match.replace('\')','')
		match=re.compile("(.+?)', '(.+)").findall(match)
		for host,stream in match:
			if host=='PutLocker' or host=='SockShare' or host=='NowVideo' or host=='VideoWeed':
				stream_url = urlresolver.HostedMediaFile(stream).resolve()
				addLink(name,host,stream_url,thumb)
		
			elif host=='YouWatch':
				response = urllib.urlopen(stream)
				link = response.read()
				response.close()
				match=re.compile('\|provider\|(.+?)\|(.+?)\|(.+?)\|(.+?)\|(.+?)\|setup\|').findall(link)
				match=str(match)
				match=match.replace('[(\'','')
				match=match.replace('\')]','')
				match=match.split("', '")
				streamurl='http://'+match[4]+'.youwatch.org:'+match[3]+'/'+match[2]+'/'+match[1]+'.'+match[0]+'?start=0'
				addLink(name,host,streamurl,thumb)
    


###################################################################################     
def setView(content, viewType):

    if content:
        xbmcplugin.setContent(int(sys.argv[1]), content)
    if addon.get_setting('auto-view') == 'true':
        xbmc.executebuiltin("Container.SetViewMode(%s)" % addon.get_setting(viewType) )
###################################################################################

def RECHERCHE():
	search_entered = ''
        keyboard = xbmc.Keyboard(search_entered, 'RECHERCHE')
        keyboard.doModal()
	if keyboard.isConfirmed():
		result = keyboard.getText() .replace(' ','+') 
		result = 'http://frenchstream.net/?s='+result
		INDEX(result)

###################################################################################

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param


def addLink(name,host,url,iconimage):
        ok=True
	fanart=IconPath+'fanart.jpg'
        liz=xbmcgui.ListItem(host, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
	liz.setProperty( "Fanart_Image", fanart )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=str(url),listitem=liz)
        return ok

def addDir(name,url,mode,iconimage):
	try:	name=name.encode('utf-8')
	except:
		pass
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
	fanart=IconPath+'fanart.jpg'
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
	liz.setProperty( "Fanart_Image", fanart )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok


params=get_params()
url=None
name=None
mode=None
icon=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
try:
        icon=urllib.unquote_plus(params["iconimage"])
except:
        pass

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)
print "Icon: "+str(icon)

if mode==None or url==None or len(url)<1:
        print ""
	xbmc.executebuiltin("Container.SetViewMode(500)")
        CATEGORIES()
       
elif mode==1:
        print ""+url
	INDEX(url)
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	p=re.compile("class='pages'>Page\s*(.+?)\s*sur").findall(link)
	page=int(float(p[0]))
	page += 1
	pp=str(page)

	url = re.sub('page/.+', 'page/', url)
	addDir('SUIVANT',url+pp,1,'')
	setView('movies', 'movie-view')
elif mode==2:
        print ""+url
        FILMPAGE(url)
elif mode==3:
	RECHERCHE()


xbmcplugin.endOfDirectory(int(sys.argv[1]))
